<template>
  <view class="bg-white h-screen flex flex-col">
    <!-- 主要内容区域 -->
    <view class="flex-1 px-6 py-4 overflow-auto">
      <!-- 消息列表 -->
      <view class="space-y-4">
        <!-- 动态消息列表 -->
        <view 
          v-for="message in messages" 
          :key="message.id"
          :class="getMessageClass(message)"
          class="rounded-xl p-4 border message-item"
        >
          <view class="flex items-start space-x-3">
            <view 
              :class="getIconClass(message)"
              class="w-10 h-10 rounded-full text-white flex items-center justify-center flex-shrink-0"
            >
              <text :class="getIconName(message)" class="fas"></text>
            </view>
            <view class="flex-1">
              <view class="flex items-center justify-between mb-2">
                <text class="font-medium text-gray-900">{{ getMessageTitle(message) }}</text>
                <text class="text-xs text-gray-500">{{ message.time }}</text>
              </view>
              <view class="text-sm text-gray-600 mb-3" v-if="message.type === 'device-share'">
                <text :class="getContentColorClass(message)">{{ message.sender }}</text>
                <text v-if="message.status === 'pending'"> 邀请您共同使用设备 </text>
                <text v-else-if="message.status === 'accepted'">您已成功加入 </text>
                <text v-else-if="message.status === 'rejected'">您已拒绝此设备分享邀请</text>
                <text class="font-medium" v-if="message.status === 'pending'">"{{ message.deviceName }}"</text>
                <text v-else-if="message.status === 'accepted'"> 的设备共享</text>
              </view>
              <text v-else class="text-sm text-gray-600 mb-3">{{ message.content }}</text>
              
              <!-- 操作按钮（仅分享邀请且待处理） -->
              <view v-if="message.type === 'device-share' && message.status === 'pending'" class="flex space-x-2">
                <button class="px-3 py-1.5 bg-blue-500 text-white rounded-lg text-xs font-medium transition-colors" @click="acceptInvite(message)">
                  接受
                </button>
                <button class="px-3 py-1.5 bg-gray-100 text-gray-600 rounded-lg text-xs font-medium transition-colors" @click="rejectInvite(message)">
                  拒绝
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { messageApi, shareApi } from '@/api/index.js'
  
  export default {
  name: 'Messages',
  data() {
    return {
      userId: null, // 当前登录用户ID
      messages: []
    }
  },
  
  onLoad() {
    this.initPage()
    this.loadMessages()
  },
  
  methods: {
    // 初始化页面
    initPage() {
      
    },

    // 加载消息列表
    async loadMessages() {
      if (!this.userId) return
      
      try {
        const result = await messageApi.getMessages({
          userId: this.userId,
          limit: 50
        })
        
        if (result.errCode === 0 && result.data && result.data.list) {

            this.messages = result.data.list.map(msg => ({
              id: msg._id,
              type: msg.message_type,
              title: msg.title,
              content: msg.content,
              sender: msg.sender_name,
              deviceName: msg.device_name,
              time: this.formatMessageTime(msg.created_at),
              status: msg.status,  // unread, read, pending, accepted, rejected
              shareId: msg.share_id  // 用于设备分享消息
            }))
        } else {
          // API失败时保留模拟数据
          console.warn('加载消息失败，使用模拟数据')
        }
      } catch (error) {
        console.error('加载消息失败:', error)
        uni.showToast({
          title: '加载消息失败',
          icon: 'none'
        })
      }
    },
    
    // 格式化消息时间
    formatMessageTime(timestamp) {
      const now = Date.now()
      const time = new Date(timestamp)
      const diff = now - time.getTime()
      
      if (diff < 60 * 1000) {
        return '刚刚'
      } else if (diff < 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 1000))}分钟前`
      } else if (diff < 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
      } else if (diff < 7 * 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
      } else {
        return time.toLocaleDateString()
      }
    },
    // 获取消息背景样式类
    getMessageClass(message) {
      if (message.type === 'device-share') {
        switch (message.status) {
          case 'pending':
            return 'bg-blue-50 border-blue-100'
          case 'accepted':
            return 'bg-green-50 border-green-100'
          case 'rejected':
            return 'bg-gray-50 border-gray-100'
          case 'read':
            return 'bg-gray-50 border-gray-100'
          default:
            return 'bg-blue-50 border-blue-100'
        }
      }
      return 'bg-gray-50 border-gray-100'
    },
    
    // 获取图标背景样式类
    getIconClass(message) {
      if (message.type === 'device-share') {
        switch (message.status) {
          case 'accepted':
            return 'bg-green-500'
          case 'rejected':
            return 'bg-gray-500'
          default:
            return 'bg-blue-500'
        }
      }
      return 'bg-gray-500'
    },
    
    // 获取图标名称
    getIconName(message) {
      if (message.type === 'device-share') {
        switch (message.status) {
          case 'accepted':
            return 'fa-check'
          case 'rejected':
            return 'fa-times'
          default:
            return 'fa-share-alt'
        }
      }
      return 'fa-info-circle'
    },
    
    // 获取消息标题
    getMessageTitle(message) {
      if (message.type === 'device-share') {
        switch (message.status) {
          case 'accepted':
            return '邀请已接受'
          case 'rejected':
            return '邀请已拒绝'
          default:
            return '设备分享邀请'
        }
      }
      return message.title || '系统通知'
    },
    
    // 获取内容颜色样式类
    getContentColorClass(message) {
      if (message.type === 'device-share') {
        switch (message.status) {
          case 'accepted':
            return 'font-medium text-green-600'
          default:
            return 'font-medium text-blue-600'
        }
      }
      return 'font-medium'
    },
    
    markAllRead() {
      // 将所有未读的设备分享邀请标记为已读
      this.messages.forEach(message => {
        if (message.type === 'device-share' && message.status === 'pending') {
          message.status = 'read'
        }
        if (message.type === 'system' && message.status === 'unread') {
          message.status = 'read'
        }
      })
      
      uni.showToast({
        title: '已标记为已读',
        icon: 'success'
      })
    },
    
    async acceptInvite(message) {
      try {
        const result = await uni.showModal({
          title: '接受邀请',
          content: `确定要接受 ${message.sender} 的设备分享邀请吗？`
        })
        
        if (result.confirm && message.shareId) {
          const apiResult = await shareApi.respondToShare({
            shareId: message.shareId,
            response: 'accept'
          })
          
          if (apiResult.errCode === 0) {
            // 更新消息状态
            message.status = 'accepted'
            message.time = '刚刚'
            
            uni.showToast({
              title: '已接受邀请',
              icon: 'success'
            })
            
            // 重新加载消息列表
            setTimeout(() => {
              this.loadMessages()
            }, 1000)
          } else {
            throw new Error(apiResult.message || '接受邀请失败')
          }
        }
      } catch (error) {
        console.error('接受邀请失败:', error)
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none'
        })
      }
    },

    async rejectInvite(message) {
      try {
        const result = await uni.showModal({
          title: '拒绝邀请',
          content: '确定要拒绝这个邀请吗？'
        })
        
        if (result.confirm && message.shareId) {
          const apiResult = await shareApi.respondToShare({
            shareId: message.shareId,
            response: 'reject'
          })
          
          if (apiResult.errCode === 0) {
            // 更新消息状态
            message.status = 'rejected'
            message.time = '刚刚'
            
            uni.showToast({
              title: '已拒绝邀请',
              icon: 'none'
            })
            
            // 重新加载消息列表
            setTimeout(() => {
              this.loadMessages()
            }, 1000)
          } else {
            throw new Error(apiResult.message || '拒绝邀请失败')
          }
        }
      } catch (error) {
        console.error('拒绝邀请失败:', error)
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
/* TailwindCSS 工具类样式 */
.bg-white { background-color: #ffffff; }
.bg-gray-50 { background-color: #f9fafb; }
.bg-gray-100 { background-color: #f3f4f6; }
.bg-gray-500 { background-color: #6b7280; }
.bg-blue-50 { background-color: #eff6ff; }
.bg-blue-100 { background-color: #dbeafe; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-blue-600 { background-color: #2563eb; }
.bg-green-50 { background-color: #f0fdf4; }
.bg-green-100 { background-color: #dcfce7; }
.bg-green-500 { background-color: #22c55e; }

.text-white { color: #ffffff; }
.text-gray-400 { color: #9ca3af; }
.text-gray-500 { color: #6b7280; }
.text-gray-600 { color: #4b5563; }
.text-gray-900 { color: #111827; }
.text-blue-500 { color: #3b82f6; }
.text-blue-600 { color: #2563eb; }
.text-green-600 { color: #16a34a; }

.h-screen { height: 100vh; }
.h-full { height: 100%; }
.w-10 { width: 80rpx; }
.w-32 { width: 256rpx; }
.h-10 { height: 80rpx; }
.h-32 { height: 256rpx; }

.flex { display: flex; }
.flex-col { flex-direction: column; }
.flex-1 { flex: 1; }

.px-6 { padding-left: 48rpx; padding-right: 48rpx; }
.px-4 { padding-left: 32rpx; padding-right: 32rpx; }
.px-3 { padding-left: 24rpx; padding-right: 24rpx; }
.py-4 { padding-top: 32rpx; padding-bottom: 32rpx; }
.py-2 { padding-top: 16rpx; padding-bottom: 16rpx; }
.py-1\.5 { padding-top: 12rpx; padding-bottom: 12rpx; }
.p-4 { padding: 32rpx; }

.mb-2 { margin-bottom: 16rpx; }
.mb-3 { margin-bottom: 24rpx; }
.mb-6 { margin-bottom: 48rpx; }

.border { border-width: 1rpx; }
.border-gray-100 { border-color: #f3f4f6; }
.border-blue-100 { border-color: #dbeafe; }
.border-green-100 { border-color: #dcfce7; }

.rounded-xl { border-radius: 24rpx; }
.rounded-lg { border-radius: 16rpx; }
.rounded-full { border-radius: 9999px; }

.items-center { align-items: center; }
.items-start { align-items: flex-start; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }
.flex-shrink-0 { flex-shrink: 0; }

.text-center { text-align: center; }
.text-xl { font-size: 40rpx; }
.text-4xl { font-size: 72rpx; }
.text-sm { font-size: 28rpx; }
.text-xs { font-size: 24rpx; }

.font-bold { font-weight: bold; }
.font-medium { font-weight: 500; }

.space-y-4 > view:not(:first-child) { margin-top: 32rpx; }
.space-x-3 > view:not(:first-child) { margin-left: 24rpx; }
.space-x-2 > view:not(:first-child) { margin-left: 16rpx; }

.transition-colors { transition: color 0.2s ease, background-color 0.2s ease; }

.overflow-auto { overflow: auto; }

/* 按钮样式 */
button {
  border-radius: 16rpx;
  font-weight: 500;
  transition: all 0.2s ease;
  border: none;
  outline: none;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  min-height: 64rpx;
}

/* Font Awesome 图标 */
.fas {
  font-family: "Font Awesome 6 Free";
  font-weight: 900;
}

.fa-share-alt:before { content: "\f1e0"; }
.fa-info-circle:before { content: "\f05a"; }
.fa-check:before { content: "\f00c"; }
.fa-times:before { content: "\f00d"; }
</style>
